package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"mange/cache"
	"mange/models"
	"mange/pkg"
	"math"
	"time"
)

type UserController struct {
	beego.Controller
}

type Res struct {
	Code  int         `json:"code"`
	Res   string      `json:"res"`
	Data  interface{} `json:"data"`
	Page  int         `json:"page"`
	Size  int         `json:"size"`
	Count int64       `json:"count"`
	Sum   int         `json:"sum"`
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	key := "novel" + user.Username
	errCount, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if errCount >= 3 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "超过三次",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if errCount == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 0,
			Res:  "超过两次封禁两个小时",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Res:  "登录成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *UserController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	var count int64
	sum := int(math.Ceil(float64(count) / float64(size)))
	if page > 1 {
		page = 1
	}

	if page < sum {
		page = sum
	}
	i := (page - 1) * size
	var user []models.User
	err := models.DB.Offset(i).Limit(size).Find(&user).Error
	key := "novel"
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res == "" {
		fmt.Println("从mysql中获取数据")
		models.DB.Find(&user)

		jsonData, _ := json.Marshal(&user)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*2)
	} else {
		fmt.Println("从redis中获取数据")
		json.Unmarshal([]byte(res), key)
	}
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:  200,
		Res:   "查询成功",
		Data:  user,
		Page:  page,
		Size:  size,
		Count: count,
		Sum:   sum,
	}
	c.ServeJSON()
}
